package com.yunfeng.web.controller;

import com.yunfeng.web.pojo.TestStudent;
import com.yunfeng.web.repository.TestStudentRepository;
import com.yunfeng.web.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

@RestController
public class TestStudentController {
    @Autowired
    private TestStudentRepository testStudentRepository;

    private ResultGenerator<TestStudent> resultGenerator = new ResultGenerator<>();

    PrintWriter pw = null;

    private String Student_ID;

    // 获取全部的数据
    @RequestMapping(path = "/findAll")
    @ResponseBody
    public Result getAllStudent() {


        Result result = resultGenerator.getSuccessResultWithMemo("数据信息获取成功");
        result.setData(testStudentRepository.findAll());
        return result;
    }

    // 查找一个
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(path = "/findByConditions")
    @ResponseBody
    public Result findByConditions(@RequestParam(value = "Student_name", required = false, defaultValue = "")
                                           String Student_name, @RequestParam(value = "Student_age", required = false, defaultValue = "0")
                                           Integer Student_age, @RequestParam(value = "Student_sex", required = false, defaultValue = "")
                                           String Student_sex, @RequestParam(value = "Student_id", required = false, defaultValue = "")
                                           String Student_id) {
        List<TestStudent> ts = testStudentRepository.findByConditions(Student_name, Student_age, Student_sex, Student_id);
        if (ts != null) {
            Result result = resultGenerator.getSuccessResult();
            result.setData(ts);
            return result;
        } else {
            Result result = resultGenerator.getFailResult("查询失败,无数据");
            return result;
        }
    }


    //插入新的数据
    @RequestMapping("/addStudent")
    @ResponseBody
    public void addNewStudent(@RequestParam("Student_name") String Student_name
            , @RequestParam(value = "Student_age", defaultValue = "0") Integer Student_age
            , @RequestParam("Student_sex") String Student_sex, HttpServletRequest req, HttpServletResponse res) throws IOException {

//        SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println(formate.parse(time));
        TestStudent ts = new TestStudent();
        //设置 编码格式
        req.setCharacterEncoding("utf-8");
        res.setContentType("application/json;charset=utf-8");
        Student_ID = UUID.randomUUID().toString().replace("-", "");

        ts.setStudent_ID(Student_ID);
        if (TextUtil.isEmpty(Student_name) || TextUtil.isEmpty(Student_sex) || Student_age == 0) {
            res.getWriter().write(CommonReturn.toPrint(0, "插入信息不能为空"));
            return;
        }

        ts.setStudent_name(Student_name);
        ts.setStudent_age(Student_age);
        ts.setStudent_sex(Student_sex);

        try {
            if (testStudentRepository.save(ts) != null)
                res.getWriter().write(CommonReturn.toPrint(1, "插入成功"));
        } catch (Exception e) {
            res.getWriter().write(CommonReturn.toPrint(-1, e.toString()));
        }

    }

    // 修改
//	@RequestMapping(path = "/updateStudent/{Student_ID}/{Student_name}/{Student_age}/{Student_sex}")
//	public @ResponseBody Result updateStudent(@PathVariable String Student_ID, @PathVariable String Student_name,
//			@PathVariable Integer Student_age, @PathVariable String Student_sex) throws Exception {
//		TestStudent student = null;
//
//		student = new TestStudent();
//		student.setStudent_ID(Student_ID);
//		student.setStudent_name(Student_name);
//		student.setStudent_age(Student_age);
//		student.setStudent_sex(Student_sex);
////		testStudentRepository.save(student);
//		if (TextUtil.isEmpty(Student_ID) || TextUtil.isEmpty(Student_name) || Student_age < 0
//				|| TextUtil.isEmpty(Student_sex)) {
//			return ResultGenerator.getFailResult("修改失败");
//
//		} else {
//			Result result = ResultGenerator.getSuccessResult();
//			result.setData(testStudentRepository.save(student));
//			return result;
//		}
//	}

    // 删除
    @SuppressWarnings("rawtypes")
    @RequestMapping(path = "/deleteStudent/{Student_ID}")
    public @ResponseBody
    Result deleteStudent(@PathVariable String Student_ID) throws IOException {
        TestStudent ts = testStudentRepository.findOne(Student_ID);
        try {
            System.out.println(ts.getStudent_ID());
            if (TextUtil.isEmpty(Student_ID) || Student_ID != ts.getStudent_ID()) {
                return resultGenerator.getFailResult("删除失败");
            } else {
                testStudentRepository.delete(Student_ID);
                return resultGenerator.getSuccessResult();
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            return resultGenerator.getFailResult("删除失败");

        }
    }

    // 分页查询
    @RequestMapping(path = "/findPageStudent/{pageNow}")
    public Page<TestStudent> findStudentNoQuery(@PathVariable Integer pageNow) {
        System.out.println(pageNow);
        Pageable pageable = new PageRequest(pageNow, 2);
        // pw.println(AppUtil.toPrint(testStudentRepository.findAll(pageable),
        // 1, "成功", "ID"));
        return this.testStudentRepository.findAll(pageable);
    }
    // -----------------------------------------------------------

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置 编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter pw=response.getWriter();
        //获得需要传参数
        String imgFile = "E:\\111.jpg";
        String base64 = Base64Util.GetImageStr(imgFile);
//        System.out.println(base64);
        String path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"+"pic"+"/"+System.currentTimeMillis()+".jpg";
        Base64Util.GenerateImage(base64, "C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\webapps\\pic\\"+System.currentTimeMillis()+".jpg");
        String photo = path;
        System.out.println(photo);
//        UserTest ut = new UserTest();
//        ut.setPhoto(photo);
//        UserTestDao utd = new UserTestDao();
//        utd.Register(photo);
//        if(photo!=""){
//            String str1 = AppUtil.toPrint(ut, 1, "插入成功", "photo");
//            pw.print(str1);
//        }else{
//            String str2 = AppUtil.toPrint(ut, 2, "插入失败", "photo");
//            response.getWriter().write(str2);
//        }
        //封装数据
        response.setContentType("text/"+photo);
        //输出数据
        pw.flush();
        pw.close();
    }
}